package logic

import (
	"context"
	"errors"
	"goods_srv/cache"
	"goods_srv/models"

	"goods_srv/goods"
	"goods_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加购物车
func (l *AddCartLogic) AddCart(in *goods.AddCartRequest) (*goods.AddCartResponse, error) {
	// todo: add your logic here and delete this line
	var err error

	//用户是否存在
	var user models.User
	user.ID = uint(in.UserId)
	err = user.GetUserInfoById()
	if err != nil {
		logx.Error("用户不存在")
		return nil, errors.New("用户不存在")
	}

	//商品是否存在
	var g models.Goods
	g.ID = uint(in.GoodsId)
	err = g.Detail()
	if err != nil {
		logx.Error("获取商品详情失败")
		return nil, errors.New("获取商品详情失败")
	}

	//商品库存是否充足
	stock, _ := cache.GetGoodsStock(int(g.ID))
	if stock < in.Num {
		logx.Error("库存不足")
		return nil, errors.New("库存不足")
	}

	//购物车中是否存在该商品
	if cache.GetCartGoods(int(in.UserId), int(in.GoodsId)) {
		//存在，更新购物车数量
		err = cache.UpdateGoodsNum(int(in.UserId), int(in.GoodsId), int(in.Num))

	} else {
		//不存在，添加购物车

		//添加购物车 如果购物车中已存在该商品 则更新数量 ，否则增加新的购物车商品
		goodsMap := map[string]interface{}{
			"goods_id": in.GoodsId,
			"user_id":  in.UserId,
			"num":      in.Num,
			"price":    g.GoodsPrice,
			"title":    g.GoodsTitle,
			"cover":    g.GoodsCover,
			"checked":  1,
		}
		err = cache.AddCart(int(in.UserId), int(in.GoodsId), goodsMap)
	}

	if err != nil {
		logx.Error("添加购物车失败")
		return nil, errors.New("添加购物车失败")
	}

	return &goods.AddCartResponse{}, nil
}
